// pages/statistics/statistics.js
const app = getApp();

Page({
  data: {
    statistics: null,
    loading: true,
    refreshing: false,
    activeTab: 0,
    tabs: ['今日统计', '本周统计', '本月统计'],
    timeRanges: ['today', 'week', 'month']
  },

  onLoad() {
    console.log('统计页面加载');
    this.loadStatistics();
  },

  onShow() {
    console.log('统计页面显示');
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  // 刷新数据
  async refreshData() {
    this.setData({ refreshing: true });
    
    try {
      await this.loadStatistics();
    } catch (error) {
      console.error('刷新数据失败:', error);
    } finally {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    }
  },

  // 加载统计信息
  async loadStatistics() {
    this.setData({ loading: true });
    app.showLoading('加载中...');

    try {
      const timeRange = this.data.timeRanges[this.data.activeTab];
      const res = await app.request({
        url: `/api/events/my-statistics?timeRange=${timeRange}`,
        method: 'GET'
      });

      this.setData({
        statistics: res.data,
        loading: false
      });
    } catch (err) {
      console.error('加载统计信息失败:', err);
      app.showError('加载失败，请重试');
      this.setData({ loading: false });
    } finally {
      app.hideLoading();
    }
  },

  // 切换标签页
  async switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeTab: index
    });
    
    // 重新加载对应时间范围的统计数据
    await this.loadStatistics();
  },

  // 查看详细列表
  viewDetailList(e) {
    const type = e.currentTarget.dataset.type;
    const timeRange = this.data.timeRanges[this.data.activeTab];
    
    wx.navigateTo({
      url: `/pages/statistics/detail?type=${type}&timeRange=${timeRange}`
    });
  },

  // 导出数据
  exportData() {
    const timeRange = this.data.timeRanges[this.data.activeTab];
    const tabName = this.data.tabs[this.data.activeTab];
    
    wx.showModal({
      title: '导出数据',
      content: `确认导出${tabName}数据？`,
      success: (res) => {
        if (res.confirm) {
          this.downloadReport(timeRange);
        }
      }
    });
  },

  // 下载报告
  async downloadReport(timeRange) {
    app.showLoading('生成报告中...');

    try {
      const res = await app.request({
        url: `/api/events/export-report?timeRange=${timeRange}`,
        method: 'GET'
      });

      if (res.data && res.data.downloadUrl) {
        // 下载文件
        wx.downloadFile({
          url: res.data.downloadUrl,
          success: (downloadRes) => {
            app.hideLoading();
            app.showSuccess('报告已下载');
            
            // 保存到相册或分享
            wx.showActionSheet({
              itemList: ['保存到相册', '分享给同事'],
              success: (actionRes) => {
                if (actionRes.tapIndex === 0) {
                  // 保存到相册
                  wx.saveImageToPhotosAlbum({
                    filePath: downloadRes.tempFilePath,
                    success: () => {
                      app.showSuccess('已保存到相册');
                    },
                    fail: () => {
                      app.showError('保存失败');
                    }
                  });
                } else if (actionRes.tapIndex === 1) {
                  // 分享
                  wx.shareAppMessage({
                    title: '应急响应统计报告',
                    path: '/pages/statistics/statistics'
                  });
                }
              }
            });
          },
          fail: () => {
            app.hideLoading();
            app.showError('下载失败');
          }
        });
      } else {
        app.hideLoading();
        app.showError('生成报告失败');
      }
    } catch (err) {
      app.hideLoading();
      console.error('下载报告失败:', err);
      app.showError('下载失败，请重试');
    }
  },

  // 刷新统计
  refreshStatistics() {
    this.loadStatistics();
  }
}); 